<script lang="ts" setup>
import UiRequestConfig from './request-config/Index.vue'
import UiServiceConfig from './service-config/Index.vue'
import UiResultConfig from './ResultConfig.vue'
import { computed, markRaw, provide, ref, onMounted  } from 'vue';
import { IStepForm, injectKeyOfEditor } from '../api-editor/utils';
import { InfoFilled } from '@element-plus/icons-vue';
import { apiAPI, apiSysConfig } from '../../api';
import { ApiConfigForm, ContentType, HttpMethod } from '../../utils/types';

const cls = 'ui-api-editor'

const props = defineProps<{ apiId?: any }>()
const loading = ref(false)
const form = ref<ApiConfigForm>({
  requestHeader: [],
  requestBody: [],
  requestPath: [],
  requestParam: [],
  serviceHeader: [],
  serviceBody: [],
  servicePath: [],
  serviceParam: [],
  apiServer: [],
  protocol: 'https',
  method: HttpMethod.POST,
  requestType: ContentType.JSON
})

const current = ref(0)

const vmRefs = ref<IStepForm[]>([])

const steps = ref([
  {
    label: '前端请求',
    vm: markRaw(UiRequestConfig),
    desc: '前端请求配置指您要登记上架的数据API，经交易中心的API网关转发后，数据API采购方在进行调用，向交易中心的API网关发起请求时的参数要求。'
  },
  {
    label: '后端服务',
    vm: markRaw(UiServiceConfig),
    desc: '后端服务配置指交易中心的API网关接收到用户请求后，向您的业务端转发请求时的相关要求。'
  },
  {
    label: '返回结果',
    vm: markRaw(UiResultConfig),
    desc: ''
  }
])

const isLast = computed(() => {
  return current.value >= steps.value.length - 1
})

const validateCurrent = () => vmRefs.value[0].validate()

const onPrev = () => {
  current.value--
}

const onNext = async () => {
  await validateCurrent()
  loading.value = true
  try {
    apiAPI.save(form.value).then(res => {
      if(current.value===0){
        form.value.versionId= res.data.versionId,
        form.value.apiId = res.data.apiId
        form.value.requestHeader= res.data.requestHeader
        form.value.requestBody= res.data.requestBody
        form.value.requestPath= res.data.requestPath
        form.value.requestParam= res.data.requestParam
      }
      current.value++
    })
  } finally {
    loading.value = false
  }
}

const onSave = async () => {
  await validateCurrent()
}

const mainDomRef = ref<HTMLDivElement>()

provide(injectKeyOfEditor, {
  scrollToBottom () {
    const el = mainDomRef.value
    el.scrollTop = el.scrollHeight
  },
  getForm () {
    return form.value
  }
})

onMounted(() => {
  if (props.apiId) {
    apiAPI.get(props.apiId)
  } else {
    apiSysConfig
      .getVars(apiSysConfig.VarType.API_CONFIG)
      .then(res => {
        form.value = { ...form.value, ...res.data }
      })
  }
})
</script>

<template>
  <div :class="cls">
    <main ref="mainDomRef" :class="`${cls}_main`">
      <div :class="[`${cls}_title`, `${cls}_page-title`]">
        <span :class="`${cls}_title-text`">定义API</span>
        <ElTooltip
          effect="light"
          placement="right"
          :popper-class="`${cls}_popper`"
          content="该过程是您将API托管至交易中心API网关的过程，需要分别定义数据API采购方调用的前端请求配置和API网关调用后端服务的配置。">
          <ElIcon>
            <InfoFilled />
          </ElIcon>
        </ElTooltip>
      </div>
      <ElSteps :active="current" simple>
        <ElStep v-for="_ in steps" :key="_.label" :title="_.label">
          <template #title>
            <div :class="`${cls}_title`">
              <span :class="`${cls}_title-text`">{{ _.label }}</span>
              <ElTooltip
                v-if="_.desc"
                effect="light"
                placement="bottom-start"
                :popper-class="`${cls}_popper`"
                :content="_.desc">
                <ElIcon>
                  <InfoFilled />
                </ElIcon>
              </ElTooltip>
            </div>
          </template>
        </ElStep>
      </ElSteps>
      <div :class="`${cls}_items`">
        <template v-for="(_, i) in steps" :key="_.label">
          <component v-if="i === current" :is="_.vm" ref="vmRefs" v-model="form" />
        </template>
      </div>
    </main>
    <footer :class="`${cls}_footer`">
      <ElButton v-if="current > 0" @click="onPrev">
        上一步
      </ElButton>
      <ElButton v-if="!isLast" type="primary" @click="onNext" :loading="loading">
        下一步
      </ElButton>
      <ElButton v-if="isLast" type="primary" @click="onSave" :loading="loading">
        完成
      </ElButton>
    </footer>
  </div>
</template>

<style lang="scss">
.ui-api-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  &_main {
    flex: 1;
    height: 0;
    overflow-y: auto;
    padding: $page-padding;
  }
  &_footer {
    text-align: center;
    padding: $page-padding;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }
  &_title {
    display: flex;
    align-items: center;
    &-text {
      margin-right: 3px;
    }
  }
  &_page-title {
    margin-bottom: 15px;
    color: var(--el-text-color-primary);
  }
  &_popper {
    max-width: 340px;
  }
  &_items {
    margin-top: $page-padding;
  }
}
</style>
